<template>
  <el-card class="box-card card-main" shadow="never">
    <div slot="header">
      <el-form
        :inline="true"
        :model="serchUser"
        class="demo-form-inline"
        label-width="90px"
        label-position="right"
        size="mini"
      >
        <el-form-item label="登陆账号：">
          <el-input v-model="serchUser.username" placeholder="请输入登陆账号" />
        </el-form-item>
        <el-form-item label="用户昵称：">
          <el-input v-model="serchUser.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户状态：">
          <el-select v-model="serchUser.status" placeholder="请选择用户状态">
            <el-option label="请选择" value />
            <el-option label="正常" value="1" />
            <el-option label="锁定" value="2" />
            <el-option label="作废" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchList">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-button size="mini" @click="handleAdd()">添加用户</el-button>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="users"
      border
      stripe
      size="small"
      style="width: auto"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="left" width="35" />
      <el-table-column prop="username" align="left" fixed label="账号" width="90" />
      <el-table-column prop="nickname" align="left" label="用户昵称" width="90" />
      <el-table-column align="left" label="角色">
        <template slot-scope="scope">
          <el-tag
            v-for="(item, index) in scope.row.roles"
            :key="index"
            size="small"
          >{{ item.description }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="80" align="left" label="账号状态">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? '正常': '' }}
          {{ scope.row.status === 2 ? '锁定': '' }}
        </template>
      </el-table-column>
      <el-table-column prop="email" align="left" width="140" label="邮箱地址" />
      <el-table-column prop="projectName" align="left" label="所属项目">
        <template slot-scope="scope">
          <el-tag
            v-for="(item, index) in scope.row.projects"
            :key="index"
            size="small"
          >{{ item.projectName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="150" align="left" label="创建时间">
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            style="padding: 3px 4px 3px 4px;margin: 1px"
            size="mini"
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.username !== 'admin'"
            type="primary"
            style="padding: 3px 4px 3px 4px;margin: 1px"
            size="mini"
          >锁定</el-button>
          <el-button
            v-if="scope.row.username !== 'admin'"
            type="danger"
            style="padding: 3px 4px 3px 4px;margin: 1px"
            size="mini"
            @click="deleteRow(scope.row)"
          >删除</el-button>
          <el-button
            type="success"
            style="padding: 3px 4px 3px 4px;margin: 1px"
            size="mini"
            @click="resetPassEdit(scope.row)"
          >重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="pageInfo.pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.pageCount"
      @size-change="changePageSize"
      @current-change="changePageNum"
    />
    <!-- 编辑用户界面 -->
    <el-dialog
      :title="editForm.title"
      :visible.sync="editFormVisible"
      width="500px"
      @closed="closeDialog('edit')"
    >
      <el-form ref="editForm" label-width="80px" :model="editForm" size="small" :rules="editRules">
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="editForm.username"
            auto-complete="off"
            placeholder="请输入用户名"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="editForm.nickname" auto-complete="off" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="锁定" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="项目" prop="projects">
          <el-checkbox-group v-model="editForm.projectIds">
            <el-checkbox
              v-for="(item, index) in projects"
              :key="index"
              :label="item.id"
            >{{ item.projectName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-checkbox-group v-model="editForm.roleIds">
            <el-checkbox
              v-for="(item, index) in roles"
              :key="index"
              :label="item.id"
            >{{ item.description }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>

    <!-- 添加用户弹窗 -->
    <el-dialog
      :title="addForm.title"
      :visible.sync="addFormVisible"
      width="500px"
      @closed="closeDialog('add')"
    >
      <el-form ref="addForm" label-width="80px" :model="addForm" size="small" :rules="addRules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="addForm.username" auto-complete="off" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            type="password"
            auto-complete="off"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
            v-model="addForm.checkPassword"
            type="password"
            auto-complete="off"
            placeholder="请确认密码"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="addForm.nickname" auto-complete="off" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="锁定" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="项目" prop="projects">
          <el-checkbox-group v-model="addForm.projectIds">
            <el-checkbox
              v-for="(item, index) in projects"
              :key="index"
              :label="item.id"
            >{{ item.projectName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-checkbox-group v-model="addForm.roleIds">
            <el-checkbox
              v-for="(item, index) in roles"
              :key="index"
              :label="item.id"
            >{{ item.description }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('add')">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submitForm('addForm')">保存</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      :title="editPassForm.title"
      :visible.sync="editPassFormVisible"
      width="500px"
      @closed="closeDialog('editPassForm')"
    >
      <el-form
        ref="editPassForm"
        label-width="90px"
        :model="editPassForm"
        size="small"
        :rules="resetRules"
      >
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="editPassForm.username"
            auto-complete="off"
            placeholder="请输入用户名"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="editPassForm.newPassword"
            type="password"
            auto-complete="off"
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="newPassword2">
          <el-input
            v-model="editPassForm.newPassword2"
            type="password"
            auto-complete="off"
            placeholder="请确认新密码"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('editPassForm')">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submitForm('editPassForm')">保存</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { requestUsers, requestEditUser, requestAllProjects, requestAddUser, deleteUser, requestResetPassWord } from '@/api/user'
import { requestAllRoles } from '@/api/role'
import { successMessage } from '@/utils/message'

export default {
  name: 'User',
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validatePass3 = (rule, value, callback) => {
      if (value !== this.editPassForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      listLoading: false,
      editFormVisible: false, // 控制编辑页面显示与隐藏
      addFormVisible: false, // 控制新增页面显示与隐藏
      editPassFormVisible: false, // 控制重置密码页面显示与隐藏
      pageInfo: { pageNum: 1, pageSize: 10, pageCount: 0 },
      serchUser: { username: '', nickname: '', status: '' },
      roles: [],
      projects: [],
      users: [], // 列表用户数据
      // 编辑
      editForm: {
        title: '',
        id: '',
        username: '',
        nickname: '',
        status: '',
        email: '',
        sex: 0,
        projectIds: [],
        roleIds: []
      },
      // 添加
      addForm: {
        title: '',
        id: '',
        password: '',
        checkPassword: '',
        username: '',
        nickname: '',
        status: 1,
        email: '',
        sex: 0,
        projectIds: [],
        roleIds: []
      },
      // 修改密码
      editPassForm: {
        title: '重置密码',
        username: '',
        newPassword: '',
        newPassword2: ''
      },
      resetRules: {
        newPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,18}$/, message: '密码由5-18位数字字母组合', trigger: 'blur' }
        ],
        newPassword2: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass3, trigger: 'blur' }
        ]
      },
      editRules: {
        nickname: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        email: [
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请填写正确格式的邮箱地址', trigger: 'blur' }
        ]
      },
      addRules: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z\d]{5,12}$/, message: '账号只能由5-12位大小写字母和数字组成', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { pattern: /^[0-9A-Za-z]{5,18}$/, message: '密码由5-18位数字字母组合', trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        email: [
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    serchInfo: function() {
      const pageInfo = this.pageInfo
      pageInfo.serchUser = this.serchUser
      return pageInfo
    }
  },
  mounted() {
    this.requestUsersInfo()
  },
  methods: {
    searchList() {
      this.requestUsersInfo()
    },
    resetSearch() {
      // 重置方法
      this.serchUser = {}
    },
    changePageNum(data) {
      // console.log('修改当前页码' + data)
      this.pageInfo.pageNum = data
      this.requestUsersInfo()
    },
    handleSelectionChange() {
      // console.log('表格插件方法')
    },
    changePageSize(data) {
      this.pageInfo.pageSize = data
      this.requestUsersInfo()
    },

    deleteRow(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(data => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.requestUsersInfo()
        })
      }).catch(() => {
        this.$message({
          type: 'success',
          message: '已取消删除'
        })
      })
    },
    // 获取用户列表数据
    requestUsersInfo() {
      this.listLoading = true
      requestUsers(this.serchInfo).then(data => {
        this.users = data.list || {}
        this.pageInfo.pageCount = data.total
        this.listLoading = false
      })
    },
    // 获取全部角色
    getAllRoles() {
      requestAllRoles().then(data => {
        this.roles = data || []
      })
    },
    // 获取全部项目
    getAllProjects() {
      requestAllProjects().then(data => {
        this.projects = data || []
      })
    },

    handleAdd() {
      // console.log('添加用户')
      this.getAllRoles()
      this.getAllProjects()
      this.addFormVisible = true
      this.addForm.title = '添加用户'
    },
    handleEdit(row) {
      this.getAllRoles()
      this.getAllProjects()
      this.editFormVisible = true
      this.editForm.title = '编辑用户'
      this.editForm.id = row.id || ''
      this.editForm.username = row.username || ''
      this.editForm.nickname = row.nickname || ''
      this.editForm.status = row.status || ''
      this.editForm.email = row.email || ''
      this.editForm.sex = row.sex || 0
      this.editForm.roleIds = row.roleIds
      const _projectIds = []
      row.projects.forEach(item => {
        _projectIds.push(item.id)
      })
      this.editForm.projectIds = _projectIds
    },
    // 重置密码
    resetPassEdit(row) {
      this.editPassFormVisible = true
      this.editPassForm.title = '重置密码'
      this.editPassForm.username = row.username
    },
    // 保存或者编辑、重置密码
    submitForm(data) {
      this.$refs[data].validate((validate) => {
        if (validate && data === 'editForm') {
          requestEditUser(this.editForm).then(
            data => {
              this.editFormVisible = false
              successMessage('保存数据成功')
              this.requestUsersInfo()
            }
          )
        } else if (validate && data === 'addForm') {
          requestAddUser(this.addForm).then(
            data => {
              this.addFormVisible = false
              this.initAddForm()
              successMessage('保存数据成功')
              this.requestUsersInfo()
            }
          )
        } else if (validate && data === 'editPassForm') {
          requestResetPassWord(this.editPassForm).then(
            data => {
              this.editPassFormVisible = false
              this.$refs['editPassForm'].resetFields()
              successMessage('保存数据成功')
              this.requestUsersInfo()
            }
          )
          // console.log('重置密码请求')
        } else {
          return false
        }
      })
    },
    // 关闭编辑、新增、增加、重置密码弹出框
    closeDialog(dialog) {
      if (dialog === 'edit') {
        this.editFormVisible = false
      } else if (dialog === 'add') {
        this.initAddForm()
        this.addFormVisible = false
      } else if (dialog === 'editPassForm') {
        this.$refs['editPassForm'].resetFields()
        this.editPassFormVisible = false
      }
    },
    initAddForm() {
      this.$refs['addForm'].resetFields()
      this.addForm.projectIds = []
      this.addForm.roleIds = []
    }
  }
}
</script>

<style scoped>
/* .el-row {
  margin-bottom: 15px;
} */
.el-tag {
  margin-right: 3px;
}
</style>
